package cn.yinuo.website.user.service.impl;

import cn.yinuo.website.common.exception.BusinessRuntimeException;
import cn.yinuo.website.user.entity.User;
import cn.yinuo.website.user.mapper.UserMapper;
import cn.yinuo.website.user.service.IUserService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shiyang
 * @since 2019-05-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService,UserDetailsService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public User loadUserByUsername(String signName) {
        Wrapper<User> wrapper = new EntityWrapper<User>().where("sign_name={0}",signName);
        List<User> tblAuthUsers = userMapper.selectList(wrapper);
        return (tblAuthUsers!=null&& tblAuthUsers.size()>0)?tblAuthUsers.get(0):null;
    }

    @Override
    public User getBySignName(String username) {
        return loadUserByUsername(username);
    }

    @Override
    public User add(User user) {
        if(user.getSignName()==null){
            throw new BusinessRuntimeException("用户登陆名不能为空");
        }
        if(user.getPassword()==null){
            throw new BusinessRuntimeException("用户密码不能为空");
        }
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        user.insert();
        return user;
    }

    @Override
    public User modify(User user) {
        if(user.getId()==null){
            throw new BusinessRuntimeException("修改操作，id不能为空");
        }
        userMapper.updateById(user);
        return userMapper.selectById(user.getId());
    }

    @Override
    public void delete(String userId) {
        userMapper.deleteById(userId);
    }

    @Override
    public User queryById(String userId) {
        return userMapper.selectById(userId);
    }


}
